package com.clouddot.baipai.ui.fragment.V_MainFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.model.beam.TargetUrl;
import com.clouddot.baipai.model.beam.getCourseById.courseInfoByid;
import com.clouddot.baipai.model.beam.getCourseById.getCourseByIdResponse;
import com.clouddot.baipai.model.beam.getCourseList.courseInfo;
import com.clouddot.baipai.model.beam.getCourseList.getCourseListResponse;
import com.clouddot.baipai.ui.activity.V_MainActivity;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.adapter.H_Adapter.courseInfoRecyclerAdapter;
import com.clouddot.baipai.ui.dialog.V_Dialog.V_ContentDailog;
import com.clouddot.baipai.ui.util.recycleView.DivierItemLinear;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.SelectedBtnUtil;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPool;
import com.clouddot.baipai.ui.util.ToastUtil;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxy on 2018/4/10.
 */

public class V_HomeWorkFragment extends BaseFragment {

    private View view;
    private Context context;
    private RecyclerView recyclerView2;
    private LinearLayout last,next;
    private Boolean isRunning = false;
    private RelativeLayout relativeLayout;
//    private RelativeLayout scanCard;
    private RelativeLayout constraintLayout;
    private ConstraintLayout constraintLayout1;
    private LinearLayout linearLayout;
    private HorizontalScrollView mHorizontalScrollView;
    private LinearLayout ll;
    private ImageView mImageView;

    private courseInfoRecyclerAdapter courseInfoRecyclerAdapter;

    private List<courseInfo> list = new ArrayList<courseInfo>();
    private List<courseInfoByid> courseInfoist = new ArrayList<courseInfoByid>();

    private float mCurrentCheckedRadioLeft; // 当前被选中的RadioButton距离左侧的距离
    private int Underline_height = 5; // 下划线高度
    private int CurrentPage = 1;
    private int pageCount = 0;
    private String currentBtn = "";
    private Button[] btnArray;
    private int buttonAmount = 4;
    private int currentTitleIndex = 0;

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();
        view = LayoutInflater.from(context).inflate(R.layout.v_f_homeworkfg,null);
    }

    @Override
    protected void initControls() {
        super.initControls();

        recyclerView2 = view.findViewById(R.id.recycle);
        recyclerView2.setLayoutManager(new LinearLayoutManager(context));
        recyclerView2.addItemDecoration(new DivierItemLinear(context,DivierItemLinear.VERTICAL_LIST));
        recyclerView2.setItemAnimator(new DefaultItemAnimator());
        courseInfoRecyclerAdapter = new courseInfoRecyclerAdapter(context,courseInfoist);
        recyclerView2.setAdapter(courseInfoRecyclerAdapter);


        last = view.findViewById(R.id.last);
        next = view.findViewById(R.id.next);
        relativeLayout = view.findViewById(R.id.loading);
        ImageView loading = view.findViewById(R.id.imgloading);
        loading.startAnimation(loadingAnim);

//        scanCard = view.findViewById(R.id.scanCard);

        linearLayout = view.findViewById(R.id.content);
        constraintLayout = view.findViewById(R.id.content1);


        ll = view.findViewById(R.id.lay);
        mImageView =  view.findViewById(R.id.img1);
        mHorizontalScrollView = view.findViewById(R.id.horizontalScrollView);
        constraintLayout1 = view.findViewById(R.id.content4);
//        mHorizontalScrollView.startAnimation(animation4);
        constraintLayout1.startAnimation(animation4);
    }

    @Override
    protected void setListener() {
        last.setOnClickListener(lastListener);
        next.setOnClickListener(nextListener);
    }


    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }


    @Override
    public void onPause() {
        super.onPause();
        if (dailog != null) dailog.closeDialog();
    }


    @Override
    public void onResume() {
        super.onResume();
        if(Env.getAppContext().isInitial) {
                linearLayout.setVisibility(View.VISIBLE);
                relativeLayout.setVisibility(View.VISIBLE);
                runThreadAction("getCourseList");
        }
    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);
        if (actionName.equals("getCourseList")) {
            if (Env.getAppContext().StudentId != null) {
                return Env.getAppPresenter().getCourseList(TargetUrl.studentId + Env.getAppContext().StudentId);
            } else {
                return Env.getAppPresenter().getCourseList(TargetUrl.classId + Env.getAppContext().classId);
            }
        } else {
            return Env.getAppPresenter().getCourseById(actionName, CurrentPage, Env.getAppContext().itemCount);
        }

    }

    @SuppressLint("NewApi")
    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if(actionName.equals("getCourseList")){
            final getCourseListResponse response = (getCourseListResponse) result;
            if(response.isSuccess()){
                list = response.list;
                currentBtn = list.get(0).getTeacherId();
                displayGroup();
                runThreadAction(currentBtn);
            }else{
                isRunning = true;
                relativeLayout.setVisibility(View.GONE);
                ToastUtil.showToast(context, response.getErrMsg());
                return;
            }
        }else{
            relativeLayout.setVisibility(View.GONE);

            getCourseByIdResponse response  = (getCourseByIdResponse) result;
            if(response.isSuccess()){
                if(!response.list.isEmpty()) {
                    courseInfoist = response.list;
                    pageCount = Integer.parseInt(response.PageCount);
                }else{
                    courseInfoist =new ArrayList<>();
                    courseInfoByid demo = new courseInfoByid();
                    demo.setDetail("");
                    demo.setTitle("当前课程无作业");
                    demo.setCreateTime("");
                    courseInfoist.add(demo);
                }
                courseInfoRecyclerAdapter = new courseInfoRecyclerAdapter(context, courseInfoist);
                courseInfoRecyclerAdapter.setbtnOnclicker(new courseInfoRecyclerAdapter.btnOnclicker() {
                    @Override
                    public void onClicked(int position) {
                        V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;


                        if (dailog != null) dailog.closeDialog();
                        dailog = new V_ContentDailog(context);
                        TextViews = dailog.getTextViews();
                        TextViews.get(0).setText(courseInfoist.get(position).getTitle());
                        TextViews.get(1).setText("发布时间："+courseInfoist.get(position).getCreateTime());
                        TextViews.get(2).setText("正在加载...");
                        final String html = EscapeUnescapeUtil.unescape(courseInfoist.get(position).getDetail());
                        ThreadPool.getInstance().execute(new Runnable() {
                            @Override
                            public void run() {
                                sp = Html.fromHtml(html, new Html.ImageGetter() {
                                    @Override
                                    public Drawable getDrawable(String source) {
                                        String s =  source.contains("http") ? source:Env.getAppContext().IP + source;
                                        InputStream is = null;
                                        try {
                                            is = (InputStream) new URL(s).getContent();
                                            Drawable d = Drawable.createFromStream(is, null);
                                            d.setBounds(0, 0, d.getIntrinsicWidth(),
                                                    d.getIntrinsicHeight());
                                            is.close();
                                            return d;
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            return null;
                                        }
                                    }
                                }, null);
                                mhandler.sendEmptyMessage(2);
                            }
                        });

                        close = dailog.getCloseView();
                        close.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;

                                dailog.closeDialog();
                            }
                        });
                        dailog.showDialog();
                    }
                });
                recyclerView2.setAdapter(courseInfoRecyclerAdapter);
            }else {
                isRunning = true;
                ToastUtil.showToast(context, response.getErrMsg());
                return;
            }
            isRunning = true;
            constraintLayout.setVisibility(View.VISIBLE);
        }


    }
    private V_ContentDailog dailog;
    private ImageView close;
    private List<TextView> TextViews;
    private Spanned sp;


    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case  2:
                    TextViews.get(2).setText(sp);
                    break;
            }
        }
    };


    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void displayGroup()
    {
        DisplayMetrics dm = new DisplayMetrics();
        mainActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels - 85;

        btnArray = new Button[list.size()];
        android.widget.LinearLayout.LayoutParams btnArrayParams = new LinearLayout.LayoutParams(width / buttonAmount, 100);
        for (int i = 0; i < list.size(); i++)
        {
            btnArray[i] = new Button(context);
            btnArray[i].setLayoutParams(btnArrayParams);
            btnArray[i].setText(list.get(i).getCourseName());
            btnArray[i].setTextSize(26);
            btnArray[i].setTag(i);
            btnArray[i].setBackground(null);
            btnArray[i].setTextColor(gray);
            btnArray[i].setOnClickListener(onClickListener);

            ll.addView(btnArray[i]);

            if (i == 0)
            {
                btnArray[0].setSelected(true);
                btnArray[0].setTextColor(blue);
                mImageView.setLayoutParams(new LinearLayout.LayoutParams(width / buttonAmount, Underline_height));
            }
        }
    }

    /**
     * 点击套餐分组的监听器
     */
    private View.OnClickListener onClickListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v) {
            if (isRunning) {
                courseInfoist.clear();
                isRunning = false;
                int tag = (Integer) v.getTag();
                SelectedBtnUtil.selectedforBtn(btnArray, btnArray[tag]);
                for (Button btn : btnArray) {
                    if (btn.getText().toString().equals(btnArray[tag].getText().toString())) {
                        btn.setTextColor(blue);
                    } else {
                        btn.setTextColor(gray);
                    }
                }
                mCurrentCheckedRadioLeft = btnArray[tag].getLeft();// 更新当前蓝色横条距离左边的距离
                mHorizontalScrollView.smoothScrollTo((int) mCurrentCheckedRadioLeft - btnArray[0].getRight(), 0);
                android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(btnArray[tag].getRight()
                        - btnArray[tag].getLeft(), Underline_height);
                params.leftMargin = (int) (tag * btnArray[0].getRight());
                mImageView.setLayoutParams(params);

                currentTitleIndex = tag;

                pageCount = 0;
                CurrentPage = 1;
                V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;


                relativeLayout.setVisibility(View.VISIBLE);
                constraintLayout.setVisibility(View.GONE);
                currentBtn = list.get(currentTitleIndex).getTeacherId();
                runThreadAction(currentBtn);

            }
        }
    };

    private View.OnClickListener lastListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;

            if (CurrentPage <= 1){
                ToastUtil.showToast(context,"当前是第一页");
                return;
            }
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView2.setVisibility(View.GONE);
            CurrentPage--;
            runThreadAction(currentBtn);
        }
    };

    private View.OnClickListener nextListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;

            if (CurrentPage >= pageCount){
                ToastUtil.showToast(context,"当前是最后一页");
                return;
            }
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView2.setVisibility(View.GONE);
            CurrentPage++;
            runThreadAction(currentBtn);
        }
    };

}
